/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-05-31 15:03:01
 */

import { delItemByIdArray, insertItem, updateItemById } from '@/utils/list';
import {
  ADD_BATCH_ITEM,
  ADD_BATCH_LIST,
  ADD_LEVEL_LIST,
  DELETE_BATCH_ITEM,
  SET_ACTIVE_BATCH,
  SET_BATCH_ITEM_PROCESS,
  SET_RECEIVE_WAY,
  SET_SELECT_RECEIVE_TYPE,
  SET_SELECTED_ITEM,
  UPDATE_BATCH_LIST
} from '../constants';

export const AccessionMgtReducer = (state, action) => {
  switch (action.type) {
    /**
     * @description: 设置选中的导入单类型
     */
    case SET_SELECT_RECEIVE_TYPE:
      return {
        ...state,
        selectReceiveType: action.data
      };
    /**
     * @description: 设置选中的导入单类型
     */
    case SET_RECEIVE_WAY:
      return {
        ...state,
        selectReceiveWay: action.data
      };

    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 加载level表格数据及相关数据
     * @param {Array} data level列表
     * @return {*}
     */
    case ADD_LEVEL_LIST: {
      return {
        ...state,
        levelList: action.data
      };
    }

    /**
     * @description: 设置批次列表
     * @param {Array} data 批次列表
     * @return {*}
     */
    case ADD_BATCH_LIST: {
      return {
        ...state,
        batchList: action.data
      };
    }

    /**
     * @description: 更新批次列表
     * @param {Array} data 批次条目
     * @return {*}
     */
    case UPDATE_BATCH_LIST: {
      return {
        ...state,
        batchList: updateItemById(action.data.id, action.data, state.batchList)
      };
    }

    /**
     * @description: 更新批次列表
     * @param {*} data websocket消息
     * @param {*} item 修改的条目
     * @return {*}
     */
    case SET_BATCH_ITEM_PROCESS: {
      const { data, item } = action;
      const { progress, message, status } = data;
      item.progress = progress;
      item.message = message;
      if (progress === 100) {
        item.status = status;
      }
      return {
        ...state,
        batchList: updateItemById(item.id, item, state.batchList)
      };
    }

    /**
     * @description: 加载level表格数据及相关数据
     * @param {Array} data level列表
     * @return {*}
     */
    case ADD_BATCH_ITEM: {
      return {
        ...state,
        batchList: insertItem(action.data, state.batchList)
      };
    }

    /**
     * @description: 加载level表格数据及相关数据
     * @param {Array} data level列表
     * @return {*}
     */
    case DELETE_BATCH_ITEM: {
      return {
        ...state,
        batchList: delItemByIdArray(action.ids, state.batchList)
      };
    }

    /**
     * @description: 设置选中的批次条目
     * @param {any} data 选中的批次条目
     * @return {*}
     */
    case SET_ACTIVE_BATCH: {
      return {
        ...state,
        activeBatch: action.data
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
